﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace Weixin.MP.UI
{
    public class HttpWebClient
    {
        private string _serverUri;
        /// <summary>
        /// 请求服务器URL地址
        /// </summary>
        public string ServerUri
        {
            get { return _serverUri; }
            set { _serverUri = value; }
        }
        private Encoding _encodType;
        /// <summary>
        /// 响应编码格式
        /// </summary>
        public Encoding EncodType
        {
            get
            {
                if (_encodType == null)
                { _encodType = Encoding.UTF8; }
                return _encodType;
            }
            set { _encodType = value; }
        }
        /// <summary>
        /// 请求的参数
        /// </summary>
        public IDictionary<string, string> QueryParameters { get; set; }
        /// <summary>
        /// 创建一个请求实例
        /// </summary>
        public HttpWebClient()
        {
            QueryParameters = new Dictionary<string, string>();
        }
        /// <summary>
        /// 获取响应的数据流（POST）
        /// </summary>
        /// <returns></returns>
        public HttpWebResponse WebResponsePost()
        {
            var query = ToQueryString(QueryParameters);
            var data = EncodType.GetBytes(query);
            var request = (HttpWebRequest)WebRequest.Create(_serverUri);
            request.Method = "POST";
            request.Timeout = 30 * 1000;//设置请求超时时间
            request.ReadWriteTimeout = 30 * 1000;
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
            request.ServicePoint.Expect100Continue = false;
            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }
            return (HttpWebResponse)request.GetResponse();
        }
        /// <summary>
        /// 获取响应的数据流（GET）
        /// </summary>
        /// <returns></returns>
        public HttpWebResponse WebResponseGet()
        {
            var query = ToQueryString(QueryParameters);
            var request = (HttpWebRequest)WebRequest.Create(_serverUri + "?" + query);
            request.Method = "GET";
            //request.ContentType = "text/html;charset=utf-8";
            request.ServicePoint.Expect100Continue = false;
            return (HttpWebResponse)request.GetResponse();
        }
        /// <summary>
        /// 获取响应的文本
        /// </summary>
        /// <returns></returns>
        public string WebResponseText(string method)
        {
            var text = string.Empty;
            if (method.ToLower() == "post")
            {
                using (var reader = new StreamReader(WebResponsePost().GetResponseStream(), EncodType))
                {
                    text = reader.ReadToEnd();
                }
            }
            else
            {
                using (var reader = new StreamReader(WebResponseGet().GetResponseStream(), EncodType))
                {
                    text = reader.ReadToEnd();
                }
            }
            return text;
        }

        /// <summary>
        /// 将一个字符串字典里的键和值转换为URI查询字符串，该方法不对键进行排序，也不对值进行Url编码
        /// </summary>
        /// <param name="dict">字典实例</param>
        /// <returns>查询字符串</returns>
        public string ToQueryString(IDictionary<string, string> dict)
        {
            if (dict.Count == 0) return string.Empty;
            var buffer = new StringBuilder();
            int count = 0;
            bool end = false;
            foreach (var key in dict.Keys)
            {
                if (count == dict.Count - 1) { end = true; }
                if (end)
                {
                    buffer.AppendFormat("{0}={1}", key, dict[key]);
                }
                else
                {
                    buffer.AppendFormat("{0}={1}&", key, dict[key]);
                }
                count++;
            }
            return buffer.ToString();
        }

    }
}
